<template>
    <view>
        <view v-if="!isLoad" class="margin-top load loading text-l text-grey"></view>
        <view class="main-admin" v-if="isAdmin && isLoad">
            <!-- parse <include src="../admin_news_form_tpl.wxml"/> -->
            <block>
                <view class="form-box shadow">
                    <view class="form-group">
                        <view class="title must">标题</view>
                    </view>

                    <view class="form-group">
                        <input placeholder="简短的标题" placeholder-class="phc" v-model="formTitle" :focus="formTitleFocus" maxlength="50" />
                    </view>
                    <view v-if="formTitleFocus" class="hint-desc error">{{ formTitleFocus }}</view>

                    <view v-if="cateIdOptions.length > 1" class="form-group arrow" id="formCateId">
                        <view class="title must">分类</view>
                        <cmpt-picker
                            id="cate-picker"
                            :sourceData="cateIdOptions"
                            @select="url($event, { type: 'picker', item: 'formCateId', tagId: 'cate-picker' })"
                            data-type="picker"
                            data-item="formCateId"
                            :item="formCateId"
                        ></cmpt-picker>
                    </view>
                    <view v-if="formCateIdFocus" class="hint-desc error">{{ formCateIdFocus }}</view>

                    <view class="form-group">
                        <view class="title must">
                            排序号
                            <text class="text-grey text-normal margin-left-xs">(小的先显示)</text>
                        </view>
                        <input placeholder="排序号，小的先显示" type="number" placeholder-class="phc" v-model="formOrder" :focus="formOrderFocus" maxlength="4" />
                    </view>
                    <view v-if="formOrderFocus" class="hint-desc error">{{ formOrderFocus }}</view>

                    <view class="form-group">
                        <view class="action text-bold text-l">简介</view>
                        <view class="action">{{ formDesc.length }}/100</view>
                    </view>

                    <view class="form-group align-start">
                        <textarea
                            name="content"
                            placeholder-class="phc"
                            placeholder="请输入本文简介，若不填写则直接取内容前100个字作为简介"
                            style="min-height: 150rpx"
                            v-model="formDesc"
                            maxlength="100"
                            :focus="formDescFocus"
                            :auto-height="true"
                        ></textarea>
                    </view>
                    <view v-if="formDescFocus" class="hint-desc error">{{ formDescFocus }}</view>

                    <view class="form-group arrow" @tap="goToContentEdit">
                        <view class="title must">
                            详细内容
                            <text class="text-grey text-normal margin-left-xs">(必填)</text>
                        </view>
                        <view :class="'form-text ' + (contentDesc == '未填写' ? 'text-orange' : '')">{{ contentDesc }}</view>
                    </view>
                    <view v-if="formContentFocus" class="hint-desc error">{{ formContentFocus }}</view>
                </view>

                <view class="form-box shadow">
                    <!-- img upload begin -->
                    <cmpt-img-upload :imgMax="1" title="封面图上传 (必填)" :isCheck="false" :imgUploadSize="10" :imgList="imgList" @upload="bindImgUploadCmpt" />
                    <!-- img upload end -->
                </view>

                <view class="form-box shadow margin-top-xs">
                    <cmpt-form-show
                        id="cmpt-form"
                        mark="cmpt-form"
                        source="admin"
                        :isCacheMatch="false"
                        :fields="fields"
                        :forms="formForms"
                        :isDefMatch="id ? false : true"
                    ></cmpt-form-show>
                </view>

                <button @tap="bindFormSubmit" class="btn-admin margin-top-xs">提交</button>
            </block>
        </view>
    </view>
</template>

<script>
import cmptImgUpload from '@/cmpts/public/img/img_upload_cmpt';
import cmptFormShow from '@/cmpts/public/form/form_show/form_show_cmpt';
import AdminBiz from '@/utils/comm/biz/admin_biz.js';
import pageHelper from '@/utils/helper/page_helper.js';
import PublicBiz from '@/utils/comm/biz/public_biz.js';
import cloudHelper from '@/utils/helper/cloud_helper.js';
import validate from '@/utils/helper/validate.js';
import AdminNewsBiz from '@/utils/biz/admin_news_biz.js';
import projectSetting from '@/utils/public/project_setting.js';

const api = require('@/api/adminapi.js');

export default {
    components: {
        cmptImgUpload,
        cmptFormShow
    },
    data() {
        return {
            isLoad: false,
            formContent: null,
            imgList: [],
            isAdmin: '',
            formTitle: null,
            formTitleFocus: null,
            cateIdOptions: [],
            formCateId: null,
            formCateIdFocus: null,
            formOrder: null,
            formOrderFocus: null,
            formDesc: null,
            formDescFocus: null,
            contentDesc: '',
            formContentFocus: null,
            fields: '',
            formForms: null,
            id: false
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        if (!AdminBiz.isAdmin(this)) {
            return;
        }
        uni.setNavigationBarTitle({
            title: projectSetting.NEWS_NAME + '-添加'
        });
        this.setData(AdminNewsBiz.initFormData()); // 初始化表单数据
        this.setData({
            isLoad: true
        });
        this.setContentDescFun();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 监听内容更新事件
        uni.$on('admin_content_updated', this.onContentUpdated);
        
        // 检查是否有缓存的内容数据
        let cachedContent = uni.getStorageSync('admin_content_edit_data');
        if (cachedContent && cachedContent.length > 0) {
            this.setData({
                formContent: cachedContent
            });
            this.setContentDescFun();
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // 移除事件监听
        uni.$off('admin_content_updated', this.onContentUpdated);
        
        // 清理缓存数据
        uni.removeStorageSync('admin_content_edit_data');
    },
    methods: {
        setContentDescFun: function () {
            AdminBiz.setContentDesc(this);
        },

        // 内容编辑相关方法
        goToContentEdit: function () {
            // 跳转前保存当前内容到缓存
            uni.setStorageSync('admin_content_edit_data', this.formContent || []);
            uni.navigateTo({
                url: '/pages/admin/content/admin_content'
            });
        },

        onContentUpdated: function (formContent) {
            // 更新本页面的内容数据
            this.setData({
                formContent: formContent
            });
            this.setContentDescFun();
        },

        model: function (e) {
            pageHelper.model(this, e);
        },

        /**
         * 数据提交
         */
        bindFormSubmit: async function () {
            if (!AdminBiz.isAdmin(this)) {
                return;
            }
            let data = this;
            if (this.formContent.length == 0) {
                return pageHelper.showModal('详细内容不能为空');
            }
            data = validate.check(data, AdminNewsBiz.CHECK_FORM, this);
            if (!data) {
                return;
            }
            let forms = this.zpSelectComponent('#cmpt-form').getForms(true);
            if (!forms) {
                return;
            }
            data.forms = forms;
            data.content = this.formContent;
            data.cateName = AdminNewsBiz.getCateName(data.cateId);
            try {
                if (this.imgList.length == 0) {
                    return pageHelper.showModal('请上传封面图');
                }

                // 提取简介
                data.desc = PublicBiz.getRichEditorDesc(data.desc, this.formContent);
                let callback = async function () {
                    PublicBiz.removeCacheList('admin-news-list');
                    PublicBiz.removeCacheList('news-list');
                    uni.navigateBack();
                };

                // console.log('data', data);
                let postData = {
                    title: data.title,
                    formContents: data.content,
                    type: data.cateId,
                    order: this.formOrder,
                    intro: data.desc,
                    // cover: Array.isArray(this.imgList) ? this.imgList.join(',') : this.imgList,
                    imgs: this.imgList
                }
                api.addNotice(postData).then(res => {
                    console.log('res', res);
                    pageHelper.showSuccToast('添加成功', 2000, callback);
                    callback();
                });
                // 先创建，再上传
                // let result = await cloudHelper.callCloudSumbit('admin/news_insert', data);
                // let newsId = result.data.id;

                // 封面图片 提交处理
                // uni.showLoading({
                //     title: '提交中...',
                //     mask: true
                // });
                // await cloudHelper.transCoverTempPics(this.imgList, 'news/', newsId, 'admin/news_update_pic');

                // // 富文本
                // let formContent = this.formContent;
                // if (formContent && formContent.length > 0) {
                //     uni.showLoading({
                //         title: '提交中...',
                //         mask: true
                //     });
                //     let content = await cloudHelper.transRichEditorTempPics(formContent, 'news/', newsId, 'admin/news_update_content');
                //     this.setData({
                //         formContent: content
                //     });
                // }
                // await cloudHelper.transFormsTempPics(forms, 'news/', newsId, 'admin/news_update_forms');
                // let callback = async function () {
                //     PublicBiz.removeCacheList('admin-news-list');
                //     PublicBiz.removeCacheList('news-list');
                //     uni.navigateBack();
                // };
            } catch (err) {
                console.log('CatchClause', err);
                console.log('CatchClause', err);
                console.log(err);
            }
        },

        bindImgUploadCmpt: function (e) {
            this.setData({
                imgList: e.detail
            });
        },

        url: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            pageHelper.url(e, this);
        }
    }
};
</script>
<style>
@import './admin_news_add.css';
</style>
